<template>
  <div>
    <el-card>
      <el-row>
        <el-col :span="8">
          <el-input
            placeholder="输入用户id"
            v-model="thisUserId"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="8">
          <el-button icon="el-icon-search" @click="getThisUser">搜索</el-button>
        </el-col>
      </el-row>
      <el-table :data="userForm" border style="width: 100%" stripe>
        <el-table-column prop="_id" label="用户ID" width="300">
          <template slot-scope="scope">
            <h4 @click="toUser(scope.row._id)">{{scope.row._id}}</h4>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名称" width="220">
        </el-table-column>
        <el-table-column prop="state" label="状态" width="220">
          <template slot-scope="scope">
            <el-button
              type="danger"
              plain
              v-if="scope.row.state == '0'"
              @click="isTrue(scope.row._id)"
              >封禁中,点击解禁</el-button
            >
            <el-button
              type="success"
              plain
              v-if="scope.row.state == '1'"
              @click="isFalse(scope.row._id)"
              >正常，点击封禁</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="date"
          label="注册时间"
          width="260"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button type="primary" icon="el-icon-edit" size="medium"
              >修改</el-button
            > -->
            <el-button
              type="primary"
              icon="el-icon-message"
              size="medium"
              @click="sendToUserEmail(scope.row.email)"
              >发送信息</el-button
            >
            <!-- 写邮件窗口 -->
            <el-dialog
              title="提示"
              :visible.sync="emailDialogVisible"
              width="30%"
              :show-close="false"
              :close-on-click-modal="false"
              :close-on-press-escape="false"
            >
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                v-model="textarea"
                :autosize="{ minRows: 2, maxRows: 8 }"
                resize="none"
              >
              </el-input>
              <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialogVisible">取 消</el-button>
                <el-button type="primary" @click="subThisEmail(scope.row.email)"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
            <el-button type="primary" icon="el-icon-delete" size="medium"
            @click="deleteThisUser(scope.row._id)">删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <span class="demonstration">共有{{ isLength }}条记录</span>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          layout="prev, pager, next, jumper"
          :total="isLength"
          :page-size="10"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
export default {
  created() {
    this.getUserList();
  },
  data() {
    return {
      userForm: [],
      thisUserId: "",
      isLength: 0,
      currentPage: 1,
      pageSize: 10,
      emailDialogVisible: false,
      textarea: "",
    };
  },
  methods: {
    toUser(id){
      let routeUrl = this.$router.resolve(`/touser/${id}`);
      window.open(routeUrl.href, "_blank");
    },
    async getUserList() {
      //console.log(1);
      const { data: res } = await this.$http.post("/users/showUsers", {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
      });
      this.isLength = res.num;
      this.userForm = res.data;
    },
    async isTrue(id) {
      let state = 1;
      const { data: res } = await this.$http.post(`/users/updateState/${id}`, {
        state,
      });
      if (res.status != 200) return this.$message.error("error");
      this.$message.success("success");
      if(this.thisUserId == ''){
        this.getUserList();
        return
      } else {
        this.getThisUser();
      }
    },
    async isFalse(id) {
      let state = 0;
      const { data: res } = await this.$http.post(`/users/updateState/${id}`, {
        state,
      });
      if (res.status != 200) return this.$message.error("error");
      this.$message.success("success");
       if(this.thisUserId == ''){
        this.getUserList();
        return
      } else {
        this.getThisUser();
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUserList();
    },
    async getThisUser() {
      if (this.thisUserId.length == 0) {
        this.getUserList();
        return;
      }
      if (this.thisUserId.length == 24) {
        const { data: res } = await this.$http.get(
          `/users/userGetUserData/${this.thisUserId}`
        );
        //console.log(res);
        this.userForm = [];
        this.userForm[0] = res.data;
        this.isLength = 1;
        return;
      } else {
        this.$message.error("请输入正确的id");
      }
    },
    sendToUserEmail() {
      this.emailDialogVisible = true;
    },
    closeDialogVisible() {
      this.emailDialogVisible = false;
      this.textarea = "";
    },
    async subThisEmail(e) {
        if(this.textarea.trim().length <20){
        this.$$message.error("输入字数太少，至少二十字")
        return
      }
      else{
        const {data:res} = await this.$http.post('/sendEmail/sendForWriter',{email:e,msg:this.textarea});
        if(res == "OK"){
          this.$message.success("发送成功")
          this.emailDialogVisible = false;
          this.textarea = "";
        }
      }
    },
    deleteThisUser(id){
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data:res} = await this.$http.delete(`/users/thisUser/${id}`);
          if(res == "OK"){
            this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getUserList();
          return
          } else{
            this.$message.error("删除失败！")
            return
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    }
  },
};
</script>
<style lang="less" scoped>
.el-button{
  margin-left: 3px;
}
h4:hover{
  color: blue;
  cursor: pointer;
}
</style>
